package juc.utils.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;

public class ForkJoinRecursiveTask {
    private final static int MAX_THRESHOLD = 3;

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //RecursiveTask(有返回值，建议使用这个)、RecursiveAction(无返回值)都是ForkJoinPool调度的
        final ForkJoinPool forkJoinPool = new ForkJoinPool();
        //submit(ForkJoinTask<T> task)
        //返回Future，异步回调
        ForkJoinTask<Integer> future = forkJoinPool.submit(new CalculateRecursiveTask(0, 10));
        //会阻塞，抛出异常
        Integer result = future.get();
        System.out.println(result);
    }

    private static class CalculateRecursiveTask extends RecursiveTask<Integer> {

        private final int start;
        private final int end;

        private CalculateRecursiveTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Integer compute() {
            if (end - start <= MAX_THRESHOLD) {
                return IntStream.rangeClosed(start, end).sum();
            } else {
                int middle = (start + end) / 2;
                CalculateRecursiveTask leftTask = new CalculateRecursiveTask(start, middle);
                CalculateRecursiveTask rightTask = new CalculateRecursiveTask(middle + 1, end);
                leftTask.fork();
                rightTask.fork();
                return leftTask.join() + rightTask.join();
            }
        }
    }

}
